package cn.ekuma.odbo.mobile.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import androidx.fragment.app.DialogFragment
import cn.ekuma.odbo.mobile.R
import com.openbravo.data.user.DirtyListener

abstract class AbstractOdboSampleEditorDialog<T> : DialogFragment(), DirtyListener, EditorRecordStateChangeListener {

    protected lateinit var editorRecordHolder: EditorRecordHolder<T>

    protected lateinit var frameLayout: FrameLayout

    lateinit var saveButton: Button
    lateinit var cancelButton: Button

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root=inflater.inflate(R.layout.odbc_new_container,container,false)
        frameLayout=root.findViewById(R.id.frameLayout)
        saveButton=root.findViewById(R.id.save)
        editorRecordHolder=onCreateEditorRecordHolder()
        editorRecordHolder.setDirtyListener(this)
        editorRecordHolder.setEditorRecordStateChangeListener(this)
        frameLayout.addView(editorRecordHolder.getEditorViewPanel(inflater,frameLayout), ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT))
        saveButton.setOnClickListener {
            when(editorRecordHolder.currentState()){
                EditorRecordState.INSERT -> insertNewItem(editorRecordHolder.createValue())
                EditorRecordState.EDIT  -> saveCurrentItem(editorRecordHolder.createValue())
                else->{}
            }
            dismiss()
        }
        cancelButton=root.findViewById(R.id.cancel)
        cancelButton.setOnClickListener {
            dismiss()
        }
        return root
    }


    abstract fun saveCurrentItem(item:T)

    abstract fun insertNewItem(item: T)

    abstract fun onCreateEditorRecordHolder():EditorRecordHolder<T>

    override fun changedDirty(bDirty: Boolean) {
        saveButton.isClickable=bDirty
    }

    override fun editorRecordStateChange(fromState: EditorRecordState, toState: EditorRecordState) {

    }

}